package com.hc.service.impl;

import com.hc.bean.Functions;
import com.hc.bean.GroupList;
import com.hc.bean.TreeNode;
import com.hc.dao.FunctionsDao;
import com.hc.service.FunctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class FunctionServiceImpl implements FunctionService {
    @Autowired
    private FunctionsDao functionsDao;

    @Override
    public List<TreeNode> treeNodeList(Integer aid) {
        List<Functions> functions=functionsDao.functionList(aid);
        List<TreeNode> treeNodeList =new ArrayList<>();
        for (Functions function : functions) {
            TreeNode treeNode =new TreeNode();
            treeNode.setId(function.getId());
            treeNode.setFid(function.getParentid());
            treeNode.setText(function.getName());
            treeNodeList.add(treeNode);
        }
        treeNodeList =builderTree(treeNodeList,0);
        return treeNodeList;
    }

    @Override
    public List<Functions> functions(Integer aid) {
        List<Functions> functions=functionsDao.functionList(aid);
        List<GroupList> treeNodeList =new ArrayList<>();
        for (Functions function : functions) {
            GroupList groupList =new GroupList();
            groupList.setText(function.getName());
            treeNodeList.add(groupList);
        }
        return functionsDao.functionList(aid);
    }

    private   List<TreeNode> builderTree(List<TreeNode> nodeList, Integer id){
        List<TreeNode> treeNodes =new ArrayList<>();
        for (TreeNode treeNode : nodeList) {
            /*子节点的父id是父亲的id*/
            if(treeNode.getFid()==id){
                treeNode.setChildren(builderTree(nodeList, treeNode.getId()));
                treeNodes.add(treeNode);
            }
        }
//        System.out.println("treeNodes:"+ treeNodes);
        return treeNodes;
    }

    private   List<GroupList> builderGroup(List<GroupList> groupLists, Integer id){
        List<GroupList> groupList =new ArrayList<>();

//        System.out.println("treeNodes:"+ treeNodes);
        return groupList;
    }
}
